﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MVC_Demo.Models;
using WebApplication1.Models.Database;
using System.Collections;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {

        private readonly McStoreContext _db;
        public HomeController(McStoreContext db)
        {
            _db = db;
        }
        [Route("{controller}/{action}")]
        [Route("/Index.html")]
        [Route("/")]
        public IActionResult Index()
        {
            return View();
        }


        [Route("/About.html")]
        public IActionResult About() { return View(); }

        


            [Route("/Market.html")]
            public IActionResult Market(int cid = 0)
            {

                //1.从数据库查询数据(数据库操作)
                var list = _db.Categories.ToList();
                var goods = _db.Goods.ToList();
                //2.把数据从控制器方法传递到页面
                if (cid > 0)
                {
                    goods = goods.Where(x => x.CateId == cid).ToList();
                }
                ViewData["category"] = list;
                ViewData["goods"] = goods;
                ViewData["cid"] = cid;
                return View();
            }

            [Route("/detail.html")]
            public IActionResult Detail(int id)
            {
                var good = _db.Goods.FirstOrDefault(x => x.Id == id);
                ViewData["good"] = good;
                return View();
            }


            //添加授权标签
            [Authorize]
            [Route("/UserInfo.html")]
            public IActionResult UserInfo()
            {
                //获取授权中的用户Id
                var userId = Convert.ToInt32(HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
                var userIdInt = Convert.ToInt32(userId);
                //在数据库查询用户数据
                var user = _db.Users.FirstOrDefault(x => x.UserId == userId);
                ViewData["User"] = user;
                //查询我的购物车数据
                var carList = _db.Cars.Where(x => x.UserId == userIdInt)
                    .Join(_db.Goods, x => x.GoodId, y => y.Id, (x, y) => new CarModel
                    {
                        Name = y.Name,
                        Cover = y.Cover,
                        Price = y.Price,
                        Count = x.Count,
                        GoodId = x.GoodId
                    })
                    .ToList();


                //传输购物车数据
                ViewData["CarList"] = carList;
                return View();
            }


            [Route("/Register.html")]
            public IActionResult Register()
            {
                return View();
            }

            /// <summary>
            /// 注册账号
            /// </summary>
            /// <returns></returns>
            [HttpPost]
            public IActionResult RegisterAccount(RegisterAccountRequest request)
            {
                //判断用户名是否存在
                var result = _db.Users.Any(x => x.UserName == request.UserName);
                if (result)
                    return Content("账号已存在");

                //添加数据
                var data = new User
                {
                    CreateTime = DateTime.Now,
                    Password = request.Password,
                    Photo = String.Empty,
                    UserName = request.UserName
                };
                _db.Users.Add(data);
                var row = _db.SaveChanges();
                if (row > 0)
                    return Content("注册成功");
                return Content("注册失败");
            }

            [Route("/Login.html")]
            public IActionResult Login()
            {
                return View();
            }
            public IActionResult Userinfo() { return View(); }



            /// <summary>
            /// 登录账号
            /// </summary>
            /// <returns></returns>
            /// <summary>
            /// 登录账号
            /// </summary>
            /// <returns></returns>
            [HttpPost]
            public IActionResult LoginAccount()
            {
                //获取表单数据
                var userName = (string)HttpContext.Request.Form["username"];
                var password = (string)HttpContext.Request.Form["password"];
                //数据库查询账号密码是否存在
                var user = _db.Users.FirstOrDefault(x => x.UserName == userName);
                if (user == null)
                    return Content("用户不存在");
                if (user.Password != password)
                    return Content("密码错误");

                //存在的话 走登录流程
                var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier,user.UserId.ToString()),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Thumbprint, user.Photo),
            };
                HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));
                return Content("登录成功");
                //return RedirectToAction("Index");
            }

            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
            [HttpGet]
            public IActionResult LoginOut()
            {
                HttpContext.SignOutAsync();
                return RedirectToAction("Index");
            }


            //1、在页面 获取输入的密码 点击提交按钮 发起请求

            //方法的接收 接收请求

            //修改密码 本质 数据的本质
            //用户数据的更新
            /// <summary>
            /// 更新密码的接口 
            /// </summary>
            /// <param name="request">存放着从前端拿过来的参数</param>
            /// <returns></returns>
            public IActionResult UpdatePassword(UpdatePasswordRequest request)
            {
                //1、判断旧密码是否正确
                //先把用户数据查询出来 登录的用户数据
                //获取授权后的个人信息
                var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
                //把字符串类型的用户Id转换成int类型的
                var userIdInt = Convert.ToInt32(userId);
                var user = _db.Users.FirstOrDefault(x => x.UserId == userIdInt);
                //账号是否存在
                if (user == null)
                {
                    return Content("账号信息不存在的！");
                }
                //判断请求带过来的旧密码 是否等于数据库存放的旧密码
                if (request.OldPassword != user.Password)
                {
                    return Content("旧密码不正确！");
                }

                //旧密码和新密码相同
                if (request.NewPassword == user.Password)
                {
                    return Content("旧密码和新密码相同！");
                }

                //2、把新密码更新到数据库
                user.Password = request.NewPassword;
                _db.Users.Update(user);
                //保存更改
                var row = _db.SaveChanges();
                if (row > 0)
                    return Content("修改成功！");
                return Content("修改失败！");
            }


            /// <summary>
            //     添加购物表的数据      
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>
            public IActionResult AddCar(AddCarRequest request)
            {
                //获取授权后的个人信息
                var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
                //类型转换
                var userIdInt = Convert.ToInt32(userId);

                //我们需要判断 我的当前账号购物车是否有这个商品 
                var car = _db.Cars.FirstOrDefault(x => x.UserId == userIdInt
                                && x.GoodId == request.GoodId);
                //如果有 则更新这条记录 的Count字段
                if (car != null)
                {
                    //加入购物车 +1 自增
                    car.Count++;
                    //执行更新方法
                    _db.Cars.Update(car);
                }
                //如果没有//才是新增数据
                else
                {
                    //构建 购物车模型
                    car = new Car
                    {
                        CreateDate = DateTime.Now,
                        UserId = userIdInt,
                        Count = 1,
                        GoodId = request.GoodId
                    };
                    //新增数据
                    _db.Cars.Add(car);
                }
                //保存更改
                var row = _db.SaveChanges();
                if (row > 0)
                {
                    return Content("加入购物车成功");
                }
                return Content("加入购物车失败");
            }
            /// <summary>
            /// 减少购物车商品数量
            /// </summary>
            /// <param name="request"></param>
            /// <returns></returns>        我需要的是类型里面的属性  不一定需要对应
            public IActionResult RemoveCar(AddCarRequest request)
            {
                //处理数据 更新我的购物车商品数据
                //获取授权后的个人信息
                var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
                //把字符串类型的用户Id转换成int类型的
                var userIdInt = Convert.ToInt32(userId);
                var car = _db.Cars.FirstOrDefault(x => x.UserId == userIdInt && x.GoodId == request.GoodId);
                if (car == null)
                {
                    return Content("购物车商品不存在");
                }
                //当我们原来的购物车数量==1 再执行减少操作 就删掉这个数据
                if (car.Count == 1)
                {
                    //删除掉这个记录
                    _db.Cars.Remove(car);
                }
                else
                {
                    //购物车商品数量减少 不应该出现少于等于0的值
                    car.Count--;
                    //更新购物车
                    _db.Cars.Update(car);
                }
                //保存更改
                var row = _db.SaveChanges();
                if (row > 0)
                {
                    return Content("减少购物车成功");
                }
                return Content("减少购物车失败");
            }
        }
    } 
